<template>
  <div class="app-container">
    <div class="page-header">
      <h2 class="page-title">{{ isEditMode ? "编辑商品" : "商品发布" }}</h2>
    </div>

    <!-- 步骤条 -->
    <el-steps
      :active="currentStep"
      finish-status="success"
      class="steps-container"
    >
      <el-step
        class="clickable-step"
        title="基本信息"
        description="填写商品基本信息"
        @click.native="handleStepClick(0)"
      ></el-step>
      <el-step
        class="clickable-step"
        title="规格属性"
        description="设置规格与库存"
        @click.native="handleStepClick(1)"
      ></el-step>
      <el-step
        class="clickable-step"
        title="商品详情"
        description="完善商品详情描述"
        @click.native="handleStepClick(2)"
      ></el-step>
      <el-step
        class="clickable-step"
        title="配送方式"
        description="配置配送策略"
        @click.native="handleStepClick(3)"
      ></el-step>
      <el-step
        class="clickable-step"
        title="沐浴露"
        description="设置购物赠送"
        @click.native="handleStepClick(4)"
      ></el-step>
    </el-steps>

    <!-- 步骤内容 -->
    <div class="step-content">
      <!-- 第一步：基本信息 -->
      <div v-show="currentStep === 0" class="step-panel">
        <div class="tab-content">
          <!-- 商品分类 -->
          <div class="form-section">
            <h3 class="section-title">商品分类</h3>
            <el-form :model="form" label-width="120px">
              <el-form-item label="商品分类:" required>
                <el-select
                  v-model="form.category_id_1"
                  placeholder="请选择一级分类"
                  @change="handleCategory1Change"
                >
                  <el-option
                    v-for="item in category1List"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
                <el-select
                  v-model="form.category_id_2"
                  placeholder="请选择二级分类"
                  @change="handleCategory2Change"
                >
                  <el-option
                    v-for="item in category2List"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-form>
          </div>

          <!-- 商品信息 -->
          <div class="form-section">
            <h3 class="section-title">商品信息</h3>
            <el-form :model="form" label-width="120px">
              <el-form-item label="商品全称:" required>
                <el-input v-model="form.title" placeholder="请输入商品全称" />
              </el-form-item>

              <el-form-item label="商品简称:">
                <el-input v-model="form.alias" placeholder="请输入商品简称" />
              </el-form-item>

              <el-form-item label="商品类型:" required>
                <el-radio-group v-model="form.type">
                  <el-radio :label="1">实体商品</el-radio>
                  <el-radio :label="2">虚拟商品</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="资格商品:">
                <el-switch
                  v-model="form.is_qualification"
                  :active-value="1"
                  :inactive-value="0"
                />
              </el-form-item>

              <el-form-item label="供应商ID:" required>
                <el-input
                  v-model="form.vendor_id"
                  placeholder="请输入供应商ID"
                />
              </el-form-item>

              <el-form-item label="商品品牌:">
                <el-select
                  v-model="form.brand_id"
                  placeholder="请选择品牌"
                  filterable
                  clearable
                >
                  <el-option
                    v-for="brand in brandList"
                    :key="brand.id"
                    :label="brand.name"
                    :value="brand.id"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="商品单位:" required>
                <el-input
                  v-model="form.sku"
                  placeholder="请输入商品单位"
                  style="width: 200px;"
                />
              </el-form-item>

              <el-form-item label="排序:">
                <el-input-number
                  v-model="form.display_order"
                  :min="0"
                  :max="9999"
                  placeholder="请输入排序值"
                  controls-position="right"
                />
                <span class="form-hint">数值越大越靠前</span>
              </el-form-item>
            </el-form>
          </div>

          <!-- 商品图片与视频 -->
          <div class="form-section">
            <h3 class="section-title">商品图片与视频</h3>
            <el-form :model="form" label-width="120px">
              <el-form-item label="商品主图:" required>
                <el-upload
                  class="upload-demo"
                  :action="uploadUrl"
                  :on-success="handleMainImageSuccess"
                  :before-upload="beforeUpload"
                  :show-file-list="false"
                  :data="{ type: 'goods', attach: 'main' }"
                  :http-request="handleImageUploadRequest"
                >
                  <div class="upload-area">
                    <i class="el-icon-plus"></i>
                    <div>上传主图</div>
                    <div class="upload-hint">建议尺寸640x640像素</div>
                  </div>
                </el-upload>
                <div v-if="form.thumb" class="image-preview">
                  <img :src="form.thumb" alt="主图" />
                  <el-button type="text" @click="form.thumb = ''"
                    >删除</el-button
                  >
                </div>
              </el-form-item>

              <el-form-item label="商品其他图片:">
                <div class="image-list">
                  <el-upload
                    v-for="(item, index) in otherImages"
                    :key="index"
                    class="upload-demo"
                    :action="uploadUrl"
                    :on-success="
                      response => handleOtherImageSuccess(response, index)
                    "
                    :before-upload="beforeUpload"
                    :show-file-list="false"
                    :data="{ type: 'goods', attach: 'gallery' }"
                    :http-request="handleImageUploadRequest"
                  >
                    <div class="upload-area">
                      <i class="el-icon-plus"></i>
                    </div>
                  </el-upload>
                  <div
                    v-for="(image, index) in form.thumb_url"
                    :key="index"
                    class="image-preview"
                  >
                    <img :src="image" alt="其他图片" />
                    <el-button type="text" @click="removeOtherImage(index)"
                      >删除</el-button
                    >
                  </div>
                </div>
                <div class="upload-hint">建议尺寸640x640像素, 最多上传9张</div>
              </el-form-item>

              <el-form-item label="商品视频:">
                <el-upload
                  class="upload-demo"
                  :action="videoUploadUrl"
                  :on-success="handleVideoSuccess"
                  :before-upload="beforeVideoUpload"
                  :show-file-list="false"
                  :data="{ type: 'goods', attach: 'video' }"
                >
                  <div class="upload-area video-upload">
                    <i class="el-icon-video-camera"></i>
                    <div>上传视频</div>
                  </div>
                </el-upload>
                <div v-if="form.video_url" class="video-preview">
                  <video :src="form.video_url" controls></video>
                  <el-button type="text" @click="form.video_url = ''"
                    >删除</el-button
                  >
                </div>
              </el-form-item>
            </el-form>
          </div>

          <!-- 销售设置 -->
          <div class="form-section">
            <h3 class="section-title">销售设置</h3>
            <el-form :model="form" label-width="120px">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="价格设置*" required>
                    <div class="price-inputs">
                      <div class="price-item">
                        <el-input
                          v-model="form.price"
                          placeholder="现价"
                          class="price-input"
                        >
                          <template slot="prepend">¥</template>
                        </el-input>
                      </div>
                      <div class="price-item">
                        <el-input
                          v-model="form.market_price"
                          placeholder="原价"
                          class="price-input"
                        >
                          <template slot="prepend">¥</template>
                        </el-input>
                      </div>
                      <div class="price-item">
                        <el-input
                          v-model="form.cost_price"
                          placeholder="成本价"
                          class="price-input"
                        >
                          <template slot="prepend">¥</template>
                        </el-input>
                      </div>
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="库存数*" required>
                    <el-input
                      v-model="form.stock"
                      placeholder="库存数量"
                      style="width: 200px;"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="商品编码:">
                    <el-input
                      v-model="form.goods_sn"
                      placeholder="请输入商品编码"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="重量 (克):">
                    <el-input v-model="form.weight" placeholder="请输入重量" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="体积 (M3):">
                    <el-input v-model="form.volume" placeholder="请输入体积" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="减库存方式:">
                <el-radio-group v-model="form.reduce_stock_method">
                  <el-radio :label="0">下单减库存</el-radio>
                  <el-radio :label="1">付款减库存</el-radio>
                  <el-radio :label="2">永不减库存</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="是否可退可换货:">
                <el-switch
                  v-model="form.no_refund"
                  :active-value="0"
                  :inactive-value="1"
                  active-text="可退可换"
                  inactive-text="不可退换"
                />
              </el-form-item>

              <el-form-item label="添加到首页热销:">
                <el-switch
                  v-model="form.is_hot"
                  :active-value="1"
                  :inactive-value="0"
                />
              </el-form-item>

              <el-form-item label="是否上架:">
                <el-switch
                  v-model="form.status"
                  :active-value="1"
                  :inactive-value="0"
                />
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>

      <!-- 第二步：规格参数 -->
      <div v-show="currentStep === 1" class="step-panel">
        <div class="tab-content">
          <div class="form-section">
            <h3 class="section-title">规格设置</h3>
            <el-form :model="form" label-width="120px">
              <el-form-item label="是否启用规格属性:">
                <el-switch
                  v-model="form.has_option"
                  @change="handleOptionChange"
                  :active-value="1"
                  :inactive-value="0"
                />
                <div class="option-hint">
                  <p>1、启用商品规格后,商品的价格及库存以商品规格为准!</p>
                  <p>
                    2、每一种规格代表不同型号,例如颜色为一种规格,尺寸为一种规格,如果设置多规格,手机用户必须每一种规格都选择一个规格项,才能添加购物车或购买。
                  </p>
                </div>
              </el-form-item>
            </el-form>

            <!-- 规格定义 -->
            <div v-if="form.has_option" class="spec-section">
              <h4>商品规格</h4>
              <div
                v-for="(spec, specIndex) in specs"
                :key="specIndex"
                class="spec-item"
              >
                <el-row :gutter="20">
                  <el-col :span="6">
                    <el-input v-model="spec.title" placeholder="规格名" />
                  </el-col>
                  <el-col :span="12">
                    <div class="spec-values">
                      <el-tag
                        v-for="(value, valueIndex) in spec.items"
                        :key="valueIndex"
                        closable
                        @close="removeSpecValue(specIndex, valueIndex)"
                      >
                        {{ value.title }}
                      </el-tag>
                      <el-input
                        v-if="spec.inputVisible"
                        ref="saveTagInput"
                        v-model="spec.inputValue"
                        size="small"
                        @keyup.enter.native="handleInputConfirm(specIndex)"
                        @blur="handleInputConfirm(specIndex)"
                      />
                      <el-button
                        v-else
                        size="small"
                        @click="showInput(specIndex)"
                        >+添加规格值</el-button
                      >
                    </div>
                  </el-col>
                  <el-col :span="6">
                    <el-button type="danger" @click="removeSpec(specIndex)"
                      >删除规格</el-button
                    >
                  </el-col>
                </el-row>
              </div>

              <div class="spec-actions">
                <el-button type="primary" @click="addSpec">+新增规格</el-button>
                <el-button @click="clearAllSpecs">清除全部规格</el-button>
              </div>
            </div>

            <!-- 规格明细表格 -->
            <div
              v-if="form.has_option && specs.length > 0"
              class="spec-detail-section"
            >
              <h4>规格明细</h4>
              <el-table :data="specOptions" border>
                <el-table-column
                  v-for="spec in specs"
                  :key="spec.title"
                  :label="spec.title"
                  :prop="spec.title"
                  width="120"
                />
                <el-table-column label="库存" width="120">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.stock" size="mini" />
                  </template>
                </el-table-column>
                <el-table-column label="市场价格" width="120">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.market_price" size="mini" />
                  </template>
                </el-table-column>
                <el-table-column label="现价(元)" width="120">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.product_price" size="mini" />
                  </template>
                </el-table-column>
                <el-table-column label="成本价(元)" width="120">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.cost_price" size="mini" />
                  </template>
                </el-table-column>
                <el-table-column label="商品编码" width="120">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.goods_sn" size="mini" />
                  </template>
                </el-table-column>
                <el-table-column label="重量(克)" width="120">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.weight" size="mini" />
                  </template>
                </el-table-column>
                <el-table-column label="体积(m³)" width="120">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.volume" size="mini" />
                  </template>
                </el-table-column>
              </el-table>
              <div class="spec-summary">
                数量:{{ specOptions.length }}条;建议最多不超过100条
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 第三步：商品详情 -->
      <div v-show="currentStep === 2" class="step-panel">
        <div class="tab-content">
          <div class="form-section">
            <h3 class="section-title">商品详情</h3>
            <el-form :model="form" label-width="120px">
              <el-form-item label="商品简述:">
                <el-input
                  v-model="form.description"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入商品简述"
                />
              </el-form-item>

              <el-form-item label="商品详情:">
                <tinymce
                  :width="595"
                  :height="300"
                  v-model="form.content"
                ></tinymce>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>

      <!-- 第四步：配送方式 -->
      <div v-show="currentStep === 3" class="step-panel">
        <div class="tab-content">
          <div class="form-section">
            <h3 class="section-title">配送方式</h3>
            <el-form :model="dispatchForm" label-width="120px">
              <el-form-item label="配送方式:">
                <el-checkbox-group v-model="dispatchForm.selectedTypes">
                  <el-checkbox
                    v-for="item in dispatchOptions"
                    :key="item.value"
                    :label="item.value"
                  >
                    {{ item.label }}
                  </el-checkbox>
                </el-checkbox-group>
                <div class="form-hint">至少选择一种配送方式</div>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>

      <!-- 第五步：沐浴露 -->
      <div v-show="currentStep === 4" class="step-panel">
        <div class="tab-content">
          <div class="form-section">
            <h3 class="section-title">沐浴露赠送</h3>
            <el-form :model="showerForm" label-width="120px">
              <el-form-item label="购物赠送:" required>
                <div class="shower-form">
                  <el-input
                    v-model="showerForm.quantity"
                    placeholder="请输入赠送数量"
                    style="width: 200px;"
                  />
                  <span class="shower-unit">包</span>
                  <el-select
                    v-model="showerForm.type"
                    placeholder="选择类型"
                    style="width: 200px;"
                  >
                    <el-option
                      v-for="item in showerTypeOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                  <span class="shower-unit">沐浴露</span>
                </div>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </div>

    <!-- 步骤操作按钮 -->
    <div class="step-actions">
      <el-button @click="handleCancel">取消</el-button>
      <el-button v-if="currentStep > 0" @click="prevStep">上一步</el-button>
      <el-button
        v-if="currentStep < lastStep"
        type="primary"
        @click="nextStep"
        :disabled="!canNextStep"
      >
        下一步
      </el-button>
      <el-button
        v-if="currentStep === lastStep"
        type="primary"
        @click="handlePublish"
        :loading="publishing"
      >
        {{ isEditMode ? "保存修改" : "发布商品" }}
      </el-button>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import {
  createProduct,
  updateProduct,
  getCategories,
  getProductDetail,
  getBrands,
  getShowerTypes
} from "@/api/product";
import Tinymce from "@/components/Tinymce";

export default {
  name: "AddProduct",
  components: {
    Tinymce
  },
  data() {
    return {
      currentStep: 0, // 当前步骤
      lastStep: 4,
      publishing: false,
      loading: false, // 添加loading状态
      isEditMode: false, // 是否为编辑模式
      goodsId: null, // 商品ID（编辑模式下使用）
      uploadUrl: "/api/merchant/upload/image",
      videoUploadUrl: "/api/merchant/upload/file",

      // 表单数据
      form: {
        title: "",
        alias: "",
        type: 1,
        sku: "",
        thumb: "",
        thumb_url: [],
        video_url: "",
        category_id_1: "",
        category_id_2: "",
        category_id_3: "",
        market_price: "",
        price: "",
        cost_price: "",
        stock: "",
        goods_sn: "",
        weight: "",
        volume: "",
        vendor_id: "",
        brand_id: "",
        reduce_stock_method: 0,
        status: 1,
        has_option: 0,
        is_qualification: 0,
        is_hot: 0,
        display_order: 0,
        description: "",
        content: "",
        no_refund: 0
      },

      // 分类数据
      category1List: [],
      category2List: [],
      category3List: [],
      brandList: [],

      // 其他图片
      otherImages: [{}],

      // 规格数据
      specs: [],
      specOptions: [],

      // 配送方式
      dispatchOptions: [
        { label: "快递", value: 1 },
        { label: "自提", value: 2 }
      ],
      dispatchForm: {
        selectedTypes: []
      },

      // 沐浴露设置
      showerTypeOptions: [],
      showerForm: {
        quantity: "",
        type: ""
      }
    };
  },

  computed: {
    // 判断是否可以进入下一步
    canNextStep() {
      if (this.currentStep === 0) {
        // 第一步：基本信息验证
        return (
          this.form.title &&
          this.form.category_id_1 &&
          this.form.price &&
          this.form.stock &&
          this.form.thumb &&
          this.form.vendor_id
        );
      } else if (this.currentStep === 1) {
        // 第二步：规格参数验证（如果启用了规格，需要验证规格数据）
        if (this.form.has_option && this.specs.length > 0) {
          return this.specs.every(spec => spec.title && spec.items.length > 0);
        }
        return true; // 如果没有启用规格，直接通过
      } else if (this.currentStep === 3) {
        return this.dispatchForm.selectedTypes.length > 0;
      } else if (this.currentStep === 4) {
        const quantity = Number(this.showerForm.quantity);
        return !Number.isNaN(quantity) && quantity >= 0 && this.showerForm.type;
      }
      return true;
    }
  },

  created() {
    this.initPage();
    this.loadCategories();
    this.loadBrands();
    this.loadShowerTypes();
  },

  methods: {
    handleImageUpload(blobInfo, success, failure) {
      const formData = new FormData();
      formData.append("file", blobInfo.blob(), blobInfo.filename());
      axios
        .post("/api/upload", formData, {
          headers: {
            "Content-Type": "multipart/form-data"
          }
        })
        .then(response => {
          const url = response.data.url; // 假设后端返回图片的URL
          success(url); // 调用success函数，将图片插入到编辑器中
        })
        .catch(error => {
          failure("Error uploading image"); // 上传失败时调用failure函数，并显示错误信息
        });
    },
    // 初始化页面
    initPage() {
      // 检查路由参数，判断是否为编辑模式
      const goodsId = this.$route.params.id || this.$route.query.id;
      if (goodsId) {
        this.isEditMode = true;
        this.goodsId = goodsId;
        this.loadProductDetail();
      }
    },

    // 加载商品详情（编辑模式）
    async loadProductDetail() {
      this.loading = true;
      try {
        const response = await getProductDetail(this.goodsId);
        const goods = response.data.goods;

        // 填充表单数据
        this.form = {
          title: goods.title || "",
          alias: goods.alias || "",
          type: goods.type || 1,
          sku: goods.sku || "",
          thumb: goods.thumb || "",
          thumb_url: goods.thumb_url ? JSON.parse(goods.thumb_url) : [],
          video_url: goods.video_url || "",
          category_id_1: goods.category_id_1 || "",
          category_id_2: goods.category_id_2 || "",
          category_id_3: goods.category_id_3 || "",
          market_price: goods.market_price || "",
          price: goods.price || "",
          cost_price: goods.cost_price || "",
          stock: goods.stock || "",
          goods_sn: goods.goods_sn || "",
          weight: goods.weight || "",
          volume: goods.volume || "",
          vendor_id: goods.vendor_id || "",
          brand_id: goods.brand_id || "",
          reduce_stock_method: goods.reduce_stock_method || 0,
          status: goods.status || 1,
          has_option: goods.has_option || 0,
          is_qualification: goods.is_qualification || 0,
          is_hot: goods.is_hot || 0,
          display_order: goods.display_order || 0,
          description: goods.description || "",
          content: goods.content || "",
          no_refund: goods.no_refund || 0
        };

        this.dispatchForm.selectedTypes = goods.dispatch_type_ids
          ? goods.dispatch_type_ids
              .split(",")
              .map(id => Number(id))
              .filter(id => !!id)
          : [];

        this.showerForm.quantity = goods.shower_gel_quantity || "";
        this.showerForm.type = goods.shower_gel_type || "";

        // 处理规格数据
        if (goods.has_option && response.data.specs) {
          this.specs = response.data.specs.map(spec => ({
            title: spec.title,
            items: spec.items || [],
            inputVisible: false,
            inputValue: ""
          }));

          // 如果有已保存的规格选项，直接使用
          if (response.data.options && response.data.options.length > 0) {
            this.specOptions = response.data.options.map(option => {
              const specObj = {};

              // 解析 specs JSON 来重建规格组合显示
              if (option.specs) {
                try {
                  const specs =
                    typeof option.specs === "string"
                      ? JSON.parse(option.specs)
                      : option.specs;

                  // 根据规格ID匹配对应的规格值
                  specs.forEach(spec => {
                    // 找到对应的规格属性
                    const specAttr = this.specs.find(
                      s => s.title === spec.spec_title || s.id === spec.spec_id
                    );
                    if (specAttr) {
                      // 找到对应的规格值
                      const specItem = specAttr.items.find(
                        item =>
                          item.id === spec.spec_item_id ||
                          item.title === spec.title
                      );
                      if (specItem) {
                        specObj[specAttr.title] = specItem.title;
                      }
                    }
                  });
                } catch (e) {
                  console.error("解析规格数据失败:", e);
                  // 如果解析失败，使用 spec_titles 作为备选方案
                  const specTitles = option.spec_titles
                    ? option.spec_titles.split(",")
                    : [];
                  this.specs.forEach((spec, index) => {
                    if (specTitles[index]) {
                      specObj[spec.title] = specTitles[index];
                    }
                  });
                }
              }

              return {
                ...specObj,
                stock: option.stock || "",
                market_price: option.market_price || "",
                product_price: option.product_price || "",
                cost_price: option.cost_price || "",
                goods_sn: option.goods_sn || "",
                weight: option.weight || "",
                volume: option.volume || ""
              };
            });
          } else {
            // 如果没有已保存的规格选项，生成新的组合
            this.generateSpecOptions();
          }
        }

        // 加载对应的分类
        if (goods.category_id_1) {
          await this.loadCategory2(goods.category_id_1);
        }
        if (goods.category_id_2) {
          await this.loadCategory3(goods.category_id_2);
        }
      } catch (error) {
        this.$message.error("加载商品详情失败");
        console.error(error);
      } finally {
        this.loading = false;
      }
    },

    // 加载分类数据
    async loadCategories() {
      try {
        const response = await getCategories();
        // 后端返回的数据结构是 { list: [...], total: 3 }
        const allCategories = response.data.list || [];
        this.category1List = allCategories.filter(item => item.level === 1);
      } catch (error) {
        this.$message.error("加载分类失败");
      }
    },

    async loadBrands() {
      try {
        const response = await getBrands({
          enabled: 1
        });
        this.brandList = response.data.list || [];
      } catch (error) {
        this.$message.error("加载品牌失败");
      }
    },

    async loadShowerTypes() {
      try {
        const response = await getShowerTypes();
        if (response.code === 200) {
          const list = (response.data && response.data.list) || [];
          this.showerTypeOptions = list.map(item => ({
            label: item.name || item.adopt_out_type_name || `类型${item.id}`,
            value: item.id
          }));
        } else {
          this.$message.error(response.msg || "获取沐浴露类型失败");
        }
      } catch (error) {
        console.error("加载沐浴露类型失败", error);
        this.$message.error("获取沐浴露类型失败");
      }
    },

    // 加载二级分类
    async loadCategory2(categoryId1) {
      try {
        const response = await getCategories();
        const allCategories = response.data.list || [];
        this.category2List = allCategories.filter(
          item => item.parent_id === categoryId1 && item.level === 2
        );
      } catch (error) {
        this.$message.error("加载子分类失败");
      }
    },

    // 加载三级分类
    async loadCategory3(categoryId2) {
      try {
        const response = await getCategories();
        const allCategories = response.data.list || [];
        this.category3List = allCategories.filter(
          item => item.parent_id === categoryId2 && item.level === 3
        );
      } catch (error) {
        this.$message.error("加载三级分类失败");
      }
    },
    async handleCategory1Change(value) {
      this.form.category_id_2 = "";
      this.form.category_id_3 = "";
      this.category2List = [];
      this.category3List = [];

      // 重新加载分类数据，获取子分类
      try {
        const response = await getCategories();
        const allCategories = response.data.list || [];
        this.category2List = allCategories.filter(
          item => item.parent_id === value && item.level === 2
        );
      } catch (error) {
        this.$message.error("加载子分类失败");
      }
    },

    // 二级分类变化
    async handleCategory2Change(value) {
      this.form.category_id_3 = "";
      this.category3List = [];

      // 重新加载分类数据，获取三级分类
      try {
        const response = await getCategories();
        const allCategories = response.data.list || [];
        this.category3List = allCategories.filter(
          item => item.parent_id === value && item.level === 3
        );
      } catch (error) {
        this.$message.error("加载三级分类失败");
      }
    },

    // 上传前验证
    beforeUpload(file) {
      const isImage = file.type.startsWith("image/");
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isImage) {
        this.$message.error("只能上传图片文件!");
        return false;
      }
      if (!isLt10M) {
        this.$message.error("图片大小不能超过 10MB!");
        return false;
      }
      return true;
    },

    // 视频上传前验证
    beforeVideoUpload(file) {
      const isVideo = file.type.startsWith("video/");
      const isLt50M = file.size / 1024 / 1024 < 50;

      if (!isVideo) {
        this.$message.error("只能上传视频文件!");
        return false;
      }
      if (!isLt50M) {
        this.$message.error("视频大小不能超过 50MB!");
        return false;
      }
      return true;
    },

    async handleImageUploadRequest(options) {
      const { file, onProgress, onSuccess, onError, data } = options;
      const uploadUrl = options.action || this.uploadUrl;
      if (!uploadUrl) {
        onError(new Error("上传地址未配置"));
        return;
      }

      try {
        const compressedFile = await this.compressImage(file, {
          maxWidth: 1280,
          maxHeight: 1280,
          quality: 0.8
        });

        const formData = new FormData();
        if (data && typeof data === "object") {
          Object.keys(data).forEach(key => {
            if (data[key] !== undefined && data[key] !== null) {
              formData.append(key, data[key]);
            }
          });
        }
        formData.append("file", compressedFile, compressedFile.name);

        const config = {
          headers: {
            "Content-Type": "multipart/form-data"
          },
          onUploadProgress: event => {
            if (event.total > 0 && typeof onProgress === "function") {
              const percent = Math.round((event.loaded / event.total) * 100);
              onProgress({ percent });
            }
          }
        };

        const response = await axios.post(uploadUrl, formData, config);
        if (response && response.data) {
          onSuccess(response.data, compressedFile);
        } else {
          throw new Error("上传返回数据异常");
        }
      } catch (error) {
        console.error("upload error", error);
        if (typeof onError === "function") {
          onError(error);
        }
        this.$message.error(error.message || "图片上传失败");
      }
    },

    async compressImage(file, options = {}) {
      const { maxWidth = 1280, maxHeight = 1280, quality = 0.8 } = options;
      if (!file.type.startsWith("image/") || file.type === "image/gif") {
        return file;
      }

      return new Promise((resolve, reject) => {
        const image = new Image();
        const url = URL.createObjectURL(file);
        image.onload = () => {
          let { width, height } = image;
          let targetWidth = width;
          let targetHeight = height;

          const maxRatio = Math.min(maxWidth / width, maxHeight / height);
          if (maxRatio < 1) {
            targetWidth = Math.round(width * maxRatio);
            targetHeight = Math.round(height * maxRatio);
          }

          const canvas = document.createElement("canvas");
          canvas.width = targetWidth;
          canvas.height = targetHeight;
          const ctx = canvas.getContext("2d");
          ctx.clearRect(0, 0, targetWidth, targetHeight);
          ctx.drawImage(image, 0, 0, targetWidth, targetHeight);

          const mimeType =
            file.type === "image/png" ? "image/png" : "image/jpeg";
          const qualityValue = mimeType === "image/png" ? undefined : quality;

          canvas.toBlob(
            blob => {
              URL.revokeObjectURL(url);
              if (!blob) {
                reject(new Error("图片压缩失败"));
                return;
              }
              const compressedFile = new File([blob], file.name, {
                type: mimeType,
                lastModified: Date.now()
              });
              if (file.uid) {
                compressedFile.uid = file.uid;
              }
              resolve(compressedFile);
            },
            mimeType,
            qualityValue
          );
        };
        image.onerror = () => {
          URL.revokeObjectURL(url);
          reject(new Error("图片加载失败"));
        };
        image.src = url;
      });
    },

    // 主图上传成功
    handleMainImageSuccess(response) {
      if (response.code == 200) {
        this.form.thumb = response.data.url;
        this.$message.success("主图上传成功");
      } else {
        this.$message.error(response.msg || "上传失败");
      }
    },

    // 其他图片上传成功
    handleOtherImageSuccess(response, index) {
      if (response.code === 200) {
        this.form.thumb_url.push(response.data.url);
        this.$message.success("图片上传成功");
      } else {
        this.$message.error(response.msg || "上传失败");
      }
    },

    // 删除其他图片
    removeOtherImage(index) {
      this.form.thumb_url.splice(index, 1);
    },

    // 视频上传成功
    handleVideoSuccess(response) {
      if (response.code == 200) {
        this.form.video_url = response.data.url;
        this.$message.success("视频上传成功");
      } else {
        this.$message.error(response.msg || "上传失败");
      }
    },

    // 规格开关变化
    handleOptionChange(value) {
      if (!value) {
        this.specs = [];
        this.specOptions = [];
      }
    },

    // 添加规格
    addSpec() {
      this.specs.push({
        title: "",
        items: [],
        inputVisible: false,
        inputValue: ""
      });
    },

    // 删除规格
    removeSpec(index) {
      this.specs.splice(index, 1);
      this.generateSpecOptions();
    },

    // 显示输入框
    showInput(specIndex) {
      this.specs[specIndex].inputVisible = true;
      this.$nextTick(() => {
        this.$refs.saveTagInput[specIndex].$refs.input.focus();
      });
    },

    // 确认输入
    handleInputConfirm(specIndex) {
      const inputValue = this.specs[specIndex].inputValue;
      if (inputValue) {
        this.specs[specIndex].items.push({ title: inputValue });
      }
      this.specs[specIndex].inputVisible = false;
      this.specs[specIndex].inputValue = "";
      this.generateSpecOptions();
    },

    // 删除规格值
    removeSpecValue(specIndex, valueIndex) {
      this.specs[specIndex].items.splice(valueIndex, 1);
      this.generateSpecOptions();
    },

    // 清除所有规格
    clearAllSpecs() {
      this.specs = [];
      this.specOptions = [];
    },

    // 生成规格选项
    generateSpecOptions() {
      if (this.specs.length === 0) {
        this.specOptions = [];
        return;
      }

      // 生成所有可能的组合
      const combinations = this.generateCombinations(this.specs);
      this.specOptions = combinations.map(combo => ({
        ...combo,
        stock: "",
        market_price: "",
        product_price: "",
        cost_price: "",
        goods_sn: "",
        weight: "",
        volume: ""
      }));
    },

    // 生成组合
    generateCombinations(specs) {
      if (specs.length === 0) return [];
      if (specs.length === 1) {
        return specs[0].items.map(item => ({
          [specs[0].title]: item.title
        }));
      }

      const result = [];
      const generate = (index, current) => {
        if (index === specs.length) {
          result.push({ ...current });
          return;
        }

        specs[index].items.forEach(item => {
          generate(index + 1, { ...current, [specs[index].title]: item.title });
        });
      };

      generate(0, {});
      return result;
    },

    // 发布商品
    async handlePublish() {
      this.publishing = true;
      try {
        await this.saveShowerSettings();
        this.$message.success(
          this.isEditMode ? "商品更新成功" : "商品发布成功"
        );
        this.$router.push({ name: "product" });
      } catch (error) {
        const message =
          (error && error.message) ||
          (this.isEditMode ? "商品更新失败" : "商品发布失败");
        this.$message.error(message);
      } finally {
        this.publishing = false;
      }
    },

    // 下一步
    async nextStep() {
      if (this.currentStep === 0) {
        // 第一步：保存基本信息
        if (!this.canNextStep) {
          this.$message.warning("请完成必填信息");
          return;
        }

        try {
          // 调用保存商品接口
          await this.saveGoodsBasicInfo();
          this.currentStep++;
        } catch (error) {
          this.$message.error("保存失败，请重试");
        }
      } else if (this.currentStep === 1) {
        // 第二步：保存规格信息
        if (!this.canNextStep) {
          this.$message.warning("请完成规格设置");
          return;
        }

        try {
          // 如果启用了规格，保存规格数据
          if (this.form.has_option) {
            await this.saveGoodsSpecs();
          }
          this.currentStep++;
        } catch (error) {
          this.$message.error("保存规格失败，请重试");
        }
      } else if (this.currentStep === 2) {
        try {
          await this.saveGoodsDetail();
          this.currentStep++;
        } catch (error) {
          this.$message.error("保存商品详情失败，请重试");
        }
      } else if (this.currentStep === 3) {
        if (!this.canNextStep) {
          this.$message.warning("请至少选择一种配送方式");
          return;
        }
        try {
          await this.saveDispatchSettings();
          this.currentStep++;
        } catch (error) {
          this.$message.error("保存配送方式失败，请重试");
        }
      } else if (this.currentStep < this.lastStep) {
        this.currentStep++;
      }
    },

    // 保存商品基本信息
    async saveGoodsBasicInfo() {
      const basicData = {
        title: this.form.title,
        alias: this.form.alias,
        type: this.form.type,
        sku: this.form.sku,
        thumb: this.form.thumb,
        thumb_url: this.form.thumb_url,
        video_url: this.form.video_url,
        vendor_id: this.form.vendor_id,
        brand_id: this.form.brand_id,
        category_id_1: this.form.category_id_1,
        category_id_2: this.form.category_id_2,
        category_id_3: this.form.category_id_3,
        market_price: this.form.market_price,
        price: this.form.price,
        cost_price: this.form.cost_price,
        stock: this.form.stock,
        goods_sn: this.form.goods_sn,
        weight: this.form.weight,
        volume: this.form.volume,
        reduce_stock_method: this.form.reduce_stock_method,
        status: this.form.status,
        is_qualification: this.form.is_qualification,
        is_hot: this.form.is_hot,
        display_order: this.form.display_order,
        has_option: 0, // 基本信息阶段暂时设为无规格，规格在第二步单独保存
        description: this.form.description,
        content: this.form.content,
        no_refund: this.form.no_refund
      };

      let response;
      if (this.isEditMode) {
        // 编辑模式：调用更新接口
        response = await updateProduct(this.goodsId, basicData, 1);
      } else {
        // 新增模式：调用创建接口
        response = await createProduct(basicData);
      }

      if (response.code == 200) {
        if (!this.isEditMode) {
          // 新增模式：保存商品ID，用于后续步骤
          this.goodsId = response.data.goods_id;
        }
        this.$message.success(
          this.isEditMode ? "商品信息更新成功" : "基本信息保存成功"
        );
      } else {
        throw new Error(response.msg || "保存失败");
      }
    },

    // 保存商品规格信息
    async saveGoodsSpecs() {
      if (!this.goodsId) {
        throw new Error("商品ID不存在，请先保存基本信息");
      }

      const specData = {
        has_option: this.form.has_option,
        specs: this.specs.map(spec => ({
          title: spec.title,
          items: spec.items.map(item => ({
            title: item.title
          }))
        })),
        options: this.specOptions.map(option => {
          // 构建规格组合数据
          const specs = [];

          // 遍历每个规格属性，找到对应的规格值
          this.specs.forEach(spec => {
            if (option[spec.title]) {
              // 找到对应的规格项
              const specItem = spec.items.find(
                item => item.title === option[spec.title]
              );
              if (specItem) {
                specs.push({
                  spec_id: spec.id || null,
                  spec_title: spec.title,
                  spec_item_id: specItem.id || null,
                  title: specItem.title
                });
              }
            }
          });

          return {
            ...option,
            specs: specs, // 添加规格组合数据
            // 确保数值类型字段正确
            stock: parseInt(option.stock) || 0,
            market_price: parseFloat(option.market_price) || 0,
            product_price: parseFloat(option.product_price) || 0,
            cost_price: parseFloat(option.cost_price) || 0,
            weight: parseFloat(option.weight) || 0,
            volume: parseFloat(option.volume) || 0
          };
        })
      };

      const response = await updateProduct(this.goodsId, specData, 2);
      if (response.code == 200) {
        this.$message.success("规格信息保存成功");
      } else {
        throw new Error(response.msg || "规格保存失败");
      }
    },

    async saveGoodsDetail() {
      if (!this.goodsId) {
        throw new Error("请先完成基本信息");
      }
      const updateData = {
        description: this.form.description,
        content: this.form.content
      };
      const response = await updateProduct(this.goodsId, updateData, 3);
      if (response.code == 200) {
        this.$message.success("商品详情保存成功");
      } else {
        throw new Error(response.msg || "商品详情保存失败");
      }
    },

    async saveDispatchSettings() {
      if (!this.goodsId) {
        throw new Error("请先完成基本信息");
      }
      if (!this.dispatchForm.selectedTypes.length) {
        throw new Error("至少选择一种配送方式");
      }
      const payload = {
        dispatch_type_ids: this.dispatchForm.selectedTypes.join(",")
      };
      const response = await updateProduct(this.goodsId, payload, 4);
      if (response.code == 200) {
        this.$message.success("配送方式保存成功");
      } else {
        throw new Error(response.msg || "配送方式保存失败");
      }
    },

    async saveShowerSettings() {
      if (!this.goodsId) {
        throw new Error("请先完成基本信息");
      }
      if (!this.showerForm.quantity || !this.showerForm.type) {
        throw new Error("请完善沐浴露赠送设置");
      }
      const payload = {
        shower_gel_quantity: Number(this.showerForm.quantity),
        shower_gel_type: this.showerForm.type
      };
      const response = await updateProduct(this.goodsId, payload, 5);
      if (response.code !== 200) {
        throw new Error(response.msg || "沐浴露赠送设置保存失败");
      }
    },

    // 上一步
    prevStep() {
      if (this.currentStep > 0) {
        this.currentStep--;
      }
    },

    // 取消
    handleCancel() {
      this.$router.go(-1);
    },

    handleStepClick(targetIndex) {
      if (targetIndex === this.currentStep) {
        return;
      }
      if (targetIndex > 0 && !this.goodsId) {
        this.$message.warning("请先完成基本信息");
        return;
      }
      this.currentStep = targetIndex;
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
}

.steps-container {
  margin-bottom: 30px;
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

  .clickable-step {
    cursor: pointer;
  }
}

.step-content {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  min-height: 500px;
}

.step-panel {
  padding: 20px;
}

.tab-content {
  padding: 20px;
}

.form-section {
  margin-bottom: 30px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 16px;
  color: #303133;
}

.upload-area {
  width: 120px;
  height: 120px;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #8c939d;
}

.upload-area:hover {
  border-color: #409eff;
}

.upload-area i {
  font-size: 28px;
  margin-bottom: 8px;
}

.upload-hint {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}

.image-preview {
  position: relative;
  display: inline-block;
  margin-right: 10px;
  margin-bottom: 10px;
}

.image-preview img {
  width: 120px;
  height: 120px;
  object-fit: cover;
  border-radius: 4px;
}

.image-preview .el-button {
  position: absolute;
  top: 5px;
  right: 5px;
  background: rgba(0, 0, 0, 0.5);
  color: #fff;
  border: none;
}

.video-upload {
  width: 200px;
  height: 120px;
}

.video-preview {
  margin-top: 10px;
}

.video-preview video {
  width: 200px;
  height: 120px;
  border-radius: 4px;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
}

.option-hint {
  margin-top: 10px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
  font-size: 12px;
  color: #606266;
}

.option-hint p {
  margin: 0 0 5px 0;
}

.spec-section {
  margin-top: 20px;
}

.spec-item {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.spec-values {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
}

.spec-actions {
  margin-top: 20px;
}

.spec-detail-section {
  margin-top: 30px;
}

.spec-summary {
  margin-top: 10px;
  font-size: 12px;
  color: #606266;
}

.step-actions {
  margin-top: 30px;
  text-align: center;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.step-actions .el-button {
  margin: 0 10px;
}

.form-hint {
  margin-left: 10px;
  font-size: 12px;
  color: #999;
}

/* 价格输入框样式 */
.price-inputs {
  display: flex;
  gap: 20px;
  align-items: flex-end;
}

.price-item {
  display: flex;
  flex-direction: column;
}

.price-item label {
  font-size: 12px;
  color: #606266;
  margin-bottom: 5px;
}

.price-input {
  width: 150px;
}

.shower-form {
  display: flex;
  align-items: center;
  gap: 10px;
}

.shower-unit {
  color: #606266;
  font-size: 14px;
}
</style>
